package model.visibility;

import java.util.LinkedList;
import java.util.List;

import model.map.GameTile;

public class VisibleMap
{
	private List<VisibleTile> visibleTiles;
	
	public VisibleMap()
	{
		visibleTiles = new LinkedList<VisibleTile>();
	}
	
	public void giveTileInfo(GameTile tile, TileBuilder b)
	{
		b.setCurrentDirection(tile.getCurrentDirection());
		b.setTerrain(tile.getTerrainType());
	}
	
	public void update(List<GameTile> curVisTiles)
	{
		resetTileVisibilities();
		
		for (GameTile gt : curVisTiles)
		{
			if (containsVisTile(gt))
			{
				VisibleTile vt = getVisTile(gt);
				vt.setVisible();
				vt.update();
			}
			else
			{
				VisibleTile vt = new VisibleTile(gt);
				visibleTiles.add(vt);
				vt.setVisible();
				vt.update();
			}
		}
	}
	
	public void build(GameTile tile, TileBuilder builder)
	{
		if (containsVisTile(tile))
			getVisTile(tile).build(builder);
		else
			builder.setVisibility(Visibility.SHROUDED);
	}

	private VisibleTile getVisTile(GameTile gt) {
		for (VisibleTile vt : visibleTiles)
			if (vt.getTile() == gt)
				return vt;
		return null;
	}
	
	public void revealResources(GameTile tile)
	{
		VisibleTile vt = getVisTile(tile);
		
		if (vt == null)
			throw new RuntimeException("OH GOD I BROKE (VisibleMap)");
		
		vt.revealResources();
	}

	private boolean containsVisTile(GameTile gt)
	{
		for (VisibleTile vt : visibleTiles)
			if (vt.getTile() == gt)
				return true;
		return false;
	}

	private void resetTileVisibilities()
	{
		for (VisibleTile vt : visibleTiles)
			vt.setNonVisible();
	}
}
